package com.yt.setclaim.server.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yt.setclaim.models.entity.ClaimArchive;
import com.yt.setclaim.models.entity.ClaimClose;
import com.yt.setclaim.models.service.ClaimArchiveService;
import com.yt.setclaim.models.vo.ClaimCloseVO;
import com.yt.setclaim.server.mapper.ClaimArchiveMapper;
import com.yt.setclaim.server.mapper.ClaimCloseMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ClaimArchiveServiceImpl extends ServiceImpl<ClaimArchiveMapper, ClaimArchive> implements ClaimArchiveService {
    
    private final ClaimCloseMapper claimCloseMapper;
    
    public ClaimArchiveServiceImpl(ClaimCloseMapper claimCloseMapper) {
        this.claimCloseMapper = claimCloseMapper;
    }
    
    @Override
    public ClaimArchive getByCloseId(Integer closeId) {
        return this.getOne(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<ClaimArchive>()
                .eq("close_id", closeId)
                .eq("is_delete", 0));
    }
    
    @Override
    public List<ClaimCloseVO> getPendingCloses() {
        // 获取所有已结案但未归档的理赔结案记录
        // 1. 首先获取所有理赔结案记录
        QueryWrapper<ClaimClose> closeQueryWrapper = new QueryWrapper<>();
        closeQueryWrapper.eq("is_delete", 0); // 未删除
        List<ClaimClose> claimCloses = claimCloseMapper.selectList(closeQueryWrapper);
        
        // 2. 过滤掉已经进行过归档的记录
        List<ClaimCloseVO> pendingCloses = new ArrayList<>();
        for (ClaimClose close : claimCloses) {
            // 检查是否已经归档过
            ClaimArchive existingArchive = this.getOne(new QueryWrapper<ClaimArchive>()
                    .eq("close_id", close.getCloseId())
                    .eq("is_delete", 0));
            
            // 如果还没有归档，则添加到待归档列表中
            if (existingArchive == null) {
                ClaimCloseVO vo = new ClaimCloseVO();
                BeanUtils.copyProperties(close, vo);
                // ID转换为字符串类型
                vo.setCloseId(String.valueOf(close.getCloseId()));
                vo.setPayId(String.valueOf(close.getPayId()));
                vo.setAdminId(String.valueOf(close.getAdminId()));
                pendingCloses.add(vo);
            }
        }
        
        return pendingCloses;
    }
}